import Message from "../../../miniprogram_npm/tdesign-miniprogram/message/index";
import { UaVideoEntity, VideoType, VideoTypeMap, VideoTypeOptions } from "../../../models/ua-card.model";
import { UaUserDeckEntity } from "../../../models/ua-user-deck.model";
import { GlobalService } from "../../../services/global.service";
import { LocalStorage } from "../../../services/local-storage.service";
import { UaVideoService } from "../../../services/ua-video.service";

// pages/video/user-video-edit/user-video-edit.page.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cover: "",
    author: '',
    url: '',
    title: "",
    aid: '',
    uploadDate: new Date(),
    shortLink: "",
    uploadDateStr: '',
    videoTypeText: '默认分类',
    videoType: VideoType.DEFAULT,
    videoTypeList: VideoTypeOptions,
    videoTypeVisible: false,
    CDN_HOST: GlobalService.CDN_HOST,
    loading: false,
    canRemove: false,
  },

  customData: {
    videoId: undefined as number | undefined,
    authorId: undefined as number | undefined,
    submiting: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options: any) {
    GlobalService.clearCurrentEditingDeckInfo();
    this.customData.videoId = options ? options.videoId : undefined;
    if (options.videoId) {
      wx.setNavigationBarTitle({
        title: '编辑B站投稿'
      });
    } else {
      wx.setNavigationBarTitle({
        title: '添加B站投稿'
      });
    }
    this.customData.authorId = LocalStorage.getUserInfo()?.id;
    if (this.customData.videoId) {
      this.initVideoInfo();
    }
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() { },

  initVideoInfo() {
    UaVideoService.findById(this.customData.videoId!).then((response: UaVideoEntity) => {
      if (response) {
        console.log(response);
        this.customData.authorId = response.userId;
        this.setData({
          title: response.title,
          author: response.author,
          cover: response.cover,
          aid: response.aid,
          uploadDate: new Date(response.uploadDate!),
          url: response.url,
          shortLink: response.shortLink,
          videoTypeText: VideoTypeMap[response.videoType!],
          videoType: response.videoType!,
          canRemove: true
        })
      }
    })
  },

  submit() {
    this.customData.submiting = true;
    if (this.customData.videoId && LocalStorage.getUserInfo()?.id === this.customData.authorId) {
      this.update();
    } else {
      this.create();
    }
  },

  create() {
    UaVideoService.createVideo({
      userId: this.customData.authorId,
      title: this.data.title,
      author: this.data.author,
      cover: this.data.cover,
      aid: this.data.aid,
      url: this.data.url,
      videoType: this.data.videoType,
      uploadDate: new Date(this.data.uploadDate),
      shortLink: this.data.shortLink
    }).then((response: UaUserDeckEntity) => {
      this.customData.submiting = false;
      if (response) {
        Message.success({
          context: this,
          offset: [20, 32],
          duration: 3000,
          content: `创建成功`,
        });
        setTimeout(() => {
          wx.navigateBack();
        }, 1000);
      }
    })
  },

  update() {
    UaVideoService.updateVideo({
      id: this.customData.videoId,
      userId: this.customData.authorId,
      title: this.data.title,
      author: this.data.author,
      cover: this.data.cover,
      aid: this.data.aid,
      url: this.data.url,
      videoType: this.data.videoType,
      uploadDate: new Date(this.data.uploadDate),
      shortLink: this.data.shortLink
    }).then((response: UaUserDeckEntity) => {
      this.customData.submiting = false;
      if (response) {
        Message.success({
          context: this,
          offset: [20, 32],
          duration: 3000,
          content: `保存成功`,
        });
        setTimeout(() => {
          wx.navigateBack();
        }, 1000);
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  shortLinkChange(e: any) {
    // 【搬运】UA携战之境 绿怪八（八号）VS蓝学马（学生会）-哔哩哔哩】 https://b23.tv/g18JGro
    const fullLink = !!e.detail.value ? e.detail.value : '';

    if (!fullLink || !fullLink.includes('https://b23.tv/')) {
      return;
    }
    let shortLink = fullLink.split(' ').pop()
    this.setData({
      shortLink,
      loading: true
    });
    UaVideoService.getBiliVideoInfo(shortLink).then((video: UaVideoEntity) => {
      this.setData({
        author: video.author ? video.author : '',
        cover: video.cover ? video.cover : '',
        title: video.title ? video.title : '',
        url: video.url ? video.url : '',
        aid: video.aid ? video.aid : '',
        uploadDate: video.uploadDate ? new Date(video.uploadDate.toString()) : undefined,
        uploadDateStr: video.uploadDate ? video.uploadDate.toString() : '',
        loading: false
      })
    })
  },

  onDelete(e: any) {
    wx.showModal({
      title: '是否删除？',
      confirmText: "删除",
      cancelText: "取消",
      showCancel: true,
      confirmColor: "#eb445a",
      success: (res) => {
        if (res.confirm) {
          UaVideoService.removeById(this.customData.videoId!).then(() => {
            Message.success({
              context: this,
              offset: [20, 32],
              duration: 3000,
              content: `删除成功`,
            });
            setTimeout(() => {
              wx.navigateBack();
            }, 1000);
          })
        }
      }
    });
  },

  save() {
    if (!this.data.shortLink) {
      Message.error({
        context: this,
        offset: [20, 32],
        duration: 3000,
        content: `请填写正确的短链接`,
      });
      return;
    }
    if (!this.data.title) {
      Message.error({
        context: this,
        offset: [20, 32],
        duration: 3000,
        content: `这个短链似乎不是正确的B站视频投稿`,
      });
      return;
    }
    if (!LocalStorage.getUserInfo()?.nickName) {
      this.editUserInfo({});
      return;
    }
    this.submit();
  },

  editUserInfo(e: any) {
    wx.showModal({
      title: '添加投稿信息前需要先完善个人信息',
      confirmText: "确定",
      cancelText: "取消",
      showCancel: true,
      success: () => {
        wx.navigateTo({
          url: '/pages/user/user-info-edit/user-info-edit.page',
        });
      }
    });
  },

  onVideoTypePicker() {
    this.setData({
      videoTypeVisible: true
    });
  },

  onVideoTypePickerCancel() {
    this.setData({
      videoTypeVisible: false
    });
  },

  onVideoTypePickerConfirm(e: any) {
    this.setData({
      videoTypeText: e.detail.label[0],
      videoType: e.detail.value[0]
    });
  },


})